package com.oracle.controller;

import com.github.pagehelper.Page;
import com.oracle.Service.impl.FeedbackService;
import com.oracle.Service.impl.OrderItemService;
import com.oracle.Service.impl.OrdersService;
import com.oracle.entity.CartItem;
import com.oracle.entity.PayOrder;
import com.oracle.entity.ResultBean;
import com.oracle.entity.ShoppingCart;
import com.oracle.pojo.*;
import com.oracle.pojo.vo.OrderVo;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.security.timestamp.HttpTimestamper;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private FeedbackService feedbackService;

    @RequestMapping("/list")
    public String list(@RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                       @RequestParam(value = "pageSize",defaultValue = "3") Integer pageSize,
                       OrderVo orderVo, Model model){
        //查询所有的orders，并查询ordersItem信息，再查询到book信息
        Integer startPage;
        Integer endPage;
        if (currentPage<1){
            currentPage = 1;
        }

        Page<Orders> pages = ordersService.selectOrders(currentPage, pageSize, orderVo);
        if (currentPage>pages.getPages()){
            pages = ordersService.selectOrders(pages.getPages(), pageSize, orderVo);
        }
        if (pages.getPages()<10){
            startPage = 1;
            endPage = pages.getPages();
        }else{
            startPage = pages.getPageNum()-4;
            endPage = pages.getPageNum()+5;
        }
        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);

        model.addAttribute("pageInfo",pages);
        model.addAttribute("orders",pages.getResult());
        model.addAttribute("orderVo",orderVo);
        return "/admin/ordersList";
    }

    @RequestMapping("/user/orderList")
    public String userOrderList(HttpSession session,Model model){
        try {
            User user = (User) session.getAttribute("userLogin");
            Integer uid = user.getUid();
            if (uid!=null&&uid!=0){
            List<Orders> list = ordersService.findSomeByUid(uid);
            if (list!=null){
                model.addAttribute("code",200);
                model.addAttribute("orders",list);
            }else{
                model.addAttribute("code",301);
            }
         }else{
             model.addAttribute("code",300);
         }
        }catch (Exception e){
           model.addAttribute("code",400);
        }
        return "/front/userorder";
    }

    @Transactional
    @RequestMapping("/user/findOrderItemByoid")
    public String OrderItems(@RequestParam(value = "oid",defaultValue = "5") Integer oid, HttpSession session){
        try {
            if (oid!=null&&oid!=0){
                List<Orderitem> list = orderItemService.findOrderItemByOid(oid);
                if (list!=null){
                    session.setAttribute("oid",oid);
                    Integer paycode = ordersService.selectPayCodeByOid(oid);
                    session.setAttribute("paycode",paycode);
                    session.setAttribute("orderItemsList",list);
                    return "redirect:/orders/user/orderList";
                }else{
                    return "redirect:/orders/user/orderList";
                }
            }
            return "redirect:/orders/user/orderList";
        }catch (Exception e){
            return "redirect:/orders/user/orderList";
        }
    }

    @Transactional
    @RequestMapping("/user/submitOrder")
    public String submitOrder(HttpSession session){
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        User userLogin = (User) session.getAttribute("userLogin");
        try{
            if (cart!=null&&cart.getTotal()!=null&&cart.getTotal()!=new BigDecimal(0)&&userLogin.getUid()!=null&&userLogin.getUid()!=0){
                Orders orders = ordersService.addNewOrder(cart.getTotal(),new Date(),userLogin.getUid());
                if (orders!=null) {
                    Integer oid = orders.getOid();
                    Map<Integer, CartItem> map = cart.getMap();
                    Collection<CartItem> values = map.values();
                    Iterator<CartItem> iterator = values.iterator();
                    Integer num = null;
                    Book book = null;
                    //将购物车中的订单小样全部存到数据库
                    while (iterator.hasNext()){
                        CartItem cartItem = iterator.next();
                        book = cartItem.getBook();
                        num = cartItem.getNum();
                        BigDecimal total = book.getBprice().multiply(new BigDecimal(num));
                        orderItemService.addNewOrderItem(oid,book.getBid(),num,book.getBprice(),total);
                    }
                    PayOrder payOrder = new PayOrder(oid+"",cart.getTotal()+"",userLogin.getRealname()+"的商品",null);
                    session.setAttribute("payOrder",payOrder);
                    return "redirect:/user/front/orderover";
                }
            }
            return "redirect:/user/front/indexView";
        }catch (Exception e){
            return "redirect:/user/front/indexView";
        }
    }

    @Transactional
    @RequestMapping("/user/overOrder")
    public String overOrder(HttpSession session,Integer oid){
        //取消订单、如果重启服务器cart就清空了，所有只能用oid来清空数据库中的数据了
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        //先清空购物车中商品
        cart.clear();
        try{
            if (oid!=null&&oid!=0){
               orderItemService.deleteOrderItemByOid(oid);
               ordersService.deleteOrdersByOid(oid);
                return "redirect:/user/front/cart";
            }
            //去购物车
            return "redirect:/user/front/cart";
        }catch (Exception e){
            return "redirect:/user/front/cart";
        }
    }


    @RequestMapping("/user/findOrderItembyOiid")
    public String findOrderItembyOiid(Integer oiid, Model model){
        try {
            if (oiid!=null&&oiid!=0){
                Orderitem orderitem = orderItemService.findOrderItemByOiid(oiid);
                if (orderitem!=null){
                    model.addAttribute("orderitem",orderitem);
                    Feedback feedback = feedbackService.findFeedbackByOiid(oiid);
                    System.out.println(feedback);
                    if (feedback!=null){
                        model.addAttribute("feedback",feedback);
                    }
                    return "/front/feedback";
                }else{
                    return "redirect:/orders/user/orderList";
                }
            }
            return "redirect:/orders/user/orderList";
        }catch (Exception e){
            return "redirect:/orders/user/orderList";
        }
    }
}
